package cn.ffcs.bpmpvc.services.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import cn.ffcs.base.model.BaseEntity;
import cn.ffcs.bpm.model.ProcTranRecord;
import cn.ffcs.bpm.model.ProcessConfigDetail;
import cn.ffcs.bpm.model.TransactProcessStatus;
import cn.ffcs.bpmpvc.dao.AppBusinessReqDao;
import cn.ffcs.bpmpvc.dao.PocReqPlanDao;
import cn.ffcs.bpmpvc.exception.FlowPvcException;
import cn.ffcs.bpmpvc.model.PocReqPlan;
import cn.ffcs.bpmpvc.services.AppBusinessReqService;
import cn.ffcs.bpmpvc.services.bean.ConfigBean;
import cn.ffcs.bpmpvc.svc.ProcessPvcService;
import cn.ffcs.bpmpvc.svc.TaskAssignBean;
import cn.ffcs.bpmpvc.svc.TaskService;
import cn.ffcs.bpmpvc.web.views.ProcessInstView;
import cn.ffcs.bpmpvc.web.views.TaskView;
import cn.ffcs.businessrequest.model.BusinessReason;
import cn.ffcs.businessrequest.model.BusinessRequest;
import cn.ffcs.businessrequest.model.DocContent;
import cn.ffcs.businessrequest.model.ProdAdvReq;
import cn.ffcs.businessrequest.model.ReqDelay;
import cn.ffcs.businessrequest.model.ReqDocu;
import cn.ffcs.businessrequest.model.ReqProgress;
import cn.ffcs.businessrequest.service.BusinessRequestService;
import cn.ffcs.organ.model.Organization;
import cn.ffcs.organ.model.Person;
import cn.ffcs.security.model.User;
import cn.ffcs.system.dict.model.Dict;
import cn.ffcs.util.context.ApplicationContextUtil;
import cn.ffcs.util.converter.DateUtil;

public class AppBusinessReqServiceImpl implements AppBusinessReqService {
	private AppBusinessReqDao appBusinessReqDao;
	private ProcessPvcService processPvcService;
	private TaskService taskService;
	@SuppressWarnings("unchecked")
	private BusinessRequestService businessRequestService;
	private PocReqPlanDao pocReqPlanDao;
	private ConfigBean configBean;
	@SuppressWarnings("unused")
	private static final String START_REQUSER_SWIMLANCE = "startReqUserSwimlance";
	private static final String PROD_ROLE_NAME = "产品经理角色";
	
	/**
	 * 变更当前办理人
	 */
	public void changeTransactor(Integer procInstId, String nowMan, BusinessReason businessReason) {
		Person person = getAppBusinessReqDao().getPerson(Integer.parseInt(nowMan));
		ProcTranRecord procTranRecord = getProcessPvcService().getFlowPvcDao().getLiveProcTranRecord(procInstId);
		TransactProcessStatus processStatus = getProcessPvcService().getFlowPvcDao().getProcessExecuteInstById(procInstId);

		procTranRecord.setTransactor(person);
		getAppBusinessReqDao().save(procTranRecord);
		processStatus.setCurrTransactor(person.getName());
		getAppBusinessReqDao().save(processStatus);
		getAppBusinessReqDao().save(businessReason);
	}

	/**
	 * 删除需求单
	 * 
	 * @param procInstId
	 */
	public void delete(Integer procInstId, String type, BusinessReason businessReason) {
		//		Logger log = (Logger) LoggerFactory.getLogger(MyGenerator.class);
		//		try {

		BusinessRequest businessRequest = null;
		ProdAdvReq prodAdvReq = null;
		Integer reqId = null;
		if ("1".equals(type)) {
			businessRequest = getAppBusinessReqDao().getBusinessRequest(procInstId);
			reqId = businessRequest.getId();
		} else {
			prodAdvReq = getAppBusinessReqDao().getProdAdvReq(procInstId);
			reqId = prodAdvReq.getId();
		}

		List<ReqDocu> reqDocuList = getAppBusinessReqDao().findDocuList(procInstId);
		String[] idArr = new String[reqDocuList.size()];
		String[] idContent = new String[reqDocuList.size()];
		ReqDocu docu = null;
		for (int i = 0; i < reqDocuList.size(); i++) {
			docu = reqDocuList.get(i);
			idArr[i] = docu.getId().toString();
			idContent[i] = docu.getContent().getId().toString();
		}
		List<ReqProgress> listReqProgress = getAppBusinessReqDao().findReqProgressList(reqId);
		for (int i = 0; i < listReqProgress.size(); i++) {
			getAppBusinessReqDao().delete((ReqProgress) listReqProgress.get(i));
		}
		ProcessInstView processInstView = getProcessPvcService().getProcessInstView(procInstId);
		List<ProcTranRecord> listProcTranRecord = processInstView.getFlowTaskList();
		for (int i = 0; i < listProcTranRecord.size(); i++) {
			ProcTranRecord procTranRecord = (ProcTranRecord) listProcTranRecord.get(i);
			ProcTranRecord procTranRecord2 = getProcessPvcService().getFlowPvcDao().getTask(procTranRecord.getId());
			// getAppBusinessReqDao().delete((ProcTranRecord)listProcTranRecord.get(i));
			getAppBusinessReqDao().delete(procTranRecord2);
		}
		TransactProcessStatus transactProcessStatus = processInstView.getProcessStatus();
		getAppBusinessReqDao().delete(transactProcessStatus);
		if (idArr.length != 0) {
			getAppBusinessReqDao().deleteDocuByIds(idArr);
		}
		if (idContent.length != 0) {
			getAppBusinessReqDao().deleteDocContentByIds(idContent);
		}
		if ("1".equals(type)) {
			businessRequest.setEnd(new Date());
			getAppBusinessReqDao().save(businessRequest);
		} else {
			prodAdvReq.setEnd(new Date());
			getAppBusinessReqDao().save(prodAdvReq);
		}
		if (businessReason != null) {
			getAppBusinessReqDao().save(businessReason);
		}
		//		} catch (Exception e) {
		//			// TODO: handle exception
		//			e.printStackTrace();
		//			log.error("delete request error: " + e.getMessage());
		//		}
	}

	/**
	 * 强制结束需求单
	 * 
	 * @param procInstId
	 */
	public void toEnd(Integer procInstId, BusinessReason businessReason) {		
		//结束流程实例对应的活动任务
		ProcessInstView processInstView = getProcessPvcService().getProcessInstView(procInstId);
		TransactProcessStatus processStatus = processInstView.getProcessStatus();
		if("inactive-root".equalsIgnoreCase(processStatus.getState())||processStatus.getEnd()!=null){
			return;
		}
		getTaskService().getFlowPvcDao().endProcessInst(String.valueOf(procInstId));
		//结束业务
		BusinessRequest businessRequest = getAppBusinessReqDao().getBusinessRequest(procInstId);
		if (businessRequest != null) {
			businessRequest.setActTime(new Date());
			getAppBusinessReqDao().save(businessRequest);
		}
		//操作说明
		if (businessReason != null) {
			getAppBusinessReqDao().save(businessReason);
		}
	}

	public ProcTranRecord saveBusinessReqAndStartFlow(String processConfigId, Person person, List<TaskAssignBean> nextTasksList, boolean isCommit, BusinessRequest businessRequest, List<File> uploads,
			List<String> fileNames) throws Exception {
		String startPersonId = null;
		// 得到发起人的名称

		if (businessRequest.getStartPersonObj() != null && businessRequest.getStartPersonObj().getId() != null) {
			Person starPerson = getAppBusinessReqDao().getPerson(businessRequest.getStartPersonObj().getId());
			businessRequest.setStartPerson(starPerson.getName());
			businessRequest.setStartDeptObj(getOrgByPerson(businessRequest.getStartPersonObj()));
			businessRequest.setStartDept(businessRequest.getStartDeptObj().getName());
			startPersonId = businessRequest.getStartPersonObj().getId().toString();
		} else {
			businessRequest.setStartPersonObj(null);
		}
		// 启动流程

		ProcessInstView processInstView = getProcessPvcService().startProcessInst(processConfigId, person, nextTasksList, isCommit, startPersonId);

		if (businessRequest.getProdPerson() == null) {
			if (StringUtils.isNotBlank(nextTasksList.get(0).getUserId())) {
				Person prodPerson = new Person();
				prodPerson.setId(Integer.valueOf(nextTasksList.get(0).getUserId()));
				businessRequest.setProdPerson(prodPerson);
			} else {
				businessRequest.setProdPerson(null);
			}
		}

		businessRequest.setBegin(new Date());
		businessRequest.setReqCode(getReqCode());
		businessRequest.setEnd(DateUtil.getMaxDate());

		if (businessRequest.getProdPerson() != null && businessRequest.getProdPerson().getId() != null) {
			businessRequest.setProdDept(getOrgByPerson(businessRequest.getProdPerson()));
			// 写入产品经理的prodPersonSwim
			String prodIdStr = businessRequest.getProdPerson().getId().toString();
			getTaskService().saveSwimlance(prodIdStr, "prodPersonSwim", processInstView.getProcessStatus().getProcinstId());
		}
		businessRequest.setProcinstId(processInstView.getProcessStatus().getProcinstId());
		getAppBusinessReqDao().save(businessRequest);

		saveDocumentType(businessRequest, processInstView.getProcTranRecord(), uploads, fileNames, null, processInstView.getProcTranRecord().getProcessStep());
		return processInstView.getProcTranRecord();
	}

	public ProcTranRecord saveProdReqAndStartFlow(String processConfigId, Person person, List<TaskAssignBean> nextTasksList, boolean isCommit, ProdAdvReq prodAdvReq, List<File> uploads,
			List<String> fileNames) throws Exception {
		// 启动流程
		ProcessInstView processInstView = getProcessPvcService().startProcessInst(processConfigId, person, nextTasksList, isCommit);
		prodAdvReq.setBegin(new Date());
		prodAdvReq.setReqCode(getReqCode());
		prodAdvReq.setStartDept(getOrgByPerson(prodAdvReq.getStartPerson()));
		if (prodAdvReq.getProdPerson() != null && prodAdvReq.getProdPerson().getId() != null) {
			prodAdvReq.setProdDept(getOrgByPerson(prodAdvReq.getProdPerson()));
			String prodIdStr = prodAdvReq.getProdPerson().getId().toString();
			getTaskService().saveSwimlance(prodIdStr, "prodPersonSwim", processInstView.getProcessStatus().getProcinstId());
		} else {
			prodAdvReq.setProdPerson(null);
		}
		prodAdvReq.setEnd(DateUtil.getMaxDate());
		prodAdvReq.setProcinstId(processInstView.getProcessStatus().getProcinstId());
		getAppBusinessReqDao().save(prodAdvReq);
		saveDocumentType(prodAdvReq, processInstView.getProcTranRecord(), uploads, fileNames, null, processInstView.getProcTranRecord().getProcessStep());
		return processInstView.getProcTranRecord();
	}

	public void saveAppDataAndCommitTask(String flowTaskId, String content, List<TaskAssignBean> nextTasksList, boolean isCommit, BusinessRequest businessRequest, List<File> uploads,
			List<String> fileNames, List<String> delDocumentIds) throws Exception {
		// 保存
		ProcTranRecord procTranRecord = null;
		// 取得业务数据
		if (isCommit) {
			procTranRecord = getTaskService().completeTask(flowTaskId, content, nextTasksList);
			// 更新swimlance
			String swinlaneName = procTranRecord.getProcessStep().getSwinlane();
			String startPersonId = businessRequest.getStartPersonObj().getId().toString();
			getTaskService().saveSwimlance(startPersonId, swinlaneName, procTranRecord.getProcinstId());

			String prodIdStr = businessRequest.getProdPerson().getId().toString();
			getTaskService().saveSwimlance(prodIdStr, "prodPersonSwim", procTranRecord.getProcinstId());

		} else {
			procTranRecord = getTaskService().saveTaskAssignUser(flowTaskId, content, nextTasksList);
		}
		getAppBusinessReqDao().save(businessRequest);
		saveDocumentType(businessRequest, procTranRecord, uploads, fileNames, delDocumentIds, procTranRecord.getProcessStep());
	}

	public void saveDataAndCommitTask(String flowTaskId, String content, List<TaskAssignBean> nextTasksList, boolean isCommit, List<File> uploads, List<String> fileNames, List<String> delDocumentIds)
			throws Exception {
		// 保存
		ProcTranRecord procTranRecord = null;
		// 取得业务数据
		BusinessRequest businessRequest = null;
		if (isCommit) {
			procTranRecord = getTaskService().completeTask(flowTaskId, content, nextTasksList);
			// 当流程结束时，更新需求单完成时间
			businessRequest = getAppBusinessReqDao().getBusinessRequest(procTranRecord.getProcinstId());
			String nodeType = procTranRecord.getProcessStep().getNodeType();
			if (TaskService.NODE_TYPE_END.equals(nodeType)) {
				// businessRequest.setEnd(new Date());
				businessRequest.setActTime(new Date());
				getAppBusinessReqDao().save(businessRequest);
			}
		} else {
			procTranRecord = getTaskService().saveTaskAssignUser(flowTaskId, content, nextTasksList);
			businessRequest = getAppBusinessReqDao().getBusinessRequest(procTranRecord.getProcinstId());
		}

		saveDocumentType(businessRequest, procTranRecord, uploads, fileNames, delDocumentIds, procTranRecord.getProcessStep());
	}

	public void saveReqPlanAndCommitTask(String flowTaskId, String content, List<TaskAssignBean> nextTasksList, boolean isCommit, BusinessRequest bsRequest, List<File> uploads,
			List<String> fileNames, List<String> delDocumentIds) throws Exception {
		// 保存
		ProcTranRecord procTranRecord = getTaskService().getFlowPvcDao().getTask(Integer.parseInt(flowTaskId), true);
		;
		// 取得业务数据
		BusinessRequest businessRequest = getAppBusinessReqDao().getBusinessRequest(procTranRecord.getProcinstId());
		businessRequest.setPlanTime(bsRequest.getPlanTime());
		if (isCommit) {
			procTranRecord = getTaskService().completeTask(procTranRecord, content, nextTasksList);
			// 删除原来时间点记录
			String reqId = businessRequest.getId().toString();
			getPocReqPlanDao().delete(reqId, "01");
			User user = ApplicationContextUtil.getUserContextObject().getCurrUser();
			PocReqPlan pocReqPlan = new PocReqPlan();
			pocReqPlan.setDelayAdv(content);
			pocReqPlan.setDelayUser(user.getPerson().getName());
			pocReqPlan.setDelayOptime(new Date());
			pocReqPlan.setDelayTime(bsRequest.getPlanTime());
			pocReqPlan.setReqId(reqId);
			pocReqPlan.setPlanType("01");
			getPocReqPlanDao().save(pocReqPlan);
		} else {
			procTranRecord = getTaskService().saveTaskAssignUser(procTranRecord, content, nextTasksList);
		}
		getAppBusinessReqDao().save(businessRequest);
		saveDocumentType(businessRequest, procTranRecord, uploads, fileNames, delDocumentIds, procTranRecord.getProcessStep());
	}

	public void saveConfirmPlanTask(String flowTaskId, String content, List<TaskAssignBean> nextTasksList, boolean isCommit, String confirmPlanCheck, List<File> uploads, List<String> fileNames,
			List<String> delDocumentIds) throws Exception {
		// 保存
		ProcTranRecord procTranRecord = getTaskService().getFlowPvcDao().getTask(Integer.parseInt(flowTaskId), true);
		;
		// 取得业务数据
		BusinessRequest businessRequest = getAppBusinessReqDao().getBusinessRequest(procTranRecord.getProcinstId());
		if (isCommit) {
			procTranRecord = getTaskService().completeTask(procTranRecord, content, nextTasksList);
			String reqId = businessRequest.getId().toString();
			User user = ApplicationContextUtil.getUserContextObject().getCurrUser();
			PocReqPlan pocReqPlan = getPocReqPlanDao().getByReqidAndType(reqId, "01");
			if (pocReqPlan == null) {
				pocReqPlan = new PocReqPlan();
				pocReqPlan.setDelayTime(businessRequest.getPlanTime());
				pocReqPlan.setDelayUser(businessRequest.getProdPerson().getName());
				pocReqPlan.setPlanType("01");
				pocReqPlan.setReqId(reqId);
			}
			pocReqPlan.setConfirmAdv(content);
			pocReqPlan.setConfirmUser(user.getPerson().getName());
			pocReqPlan.setConfirmOptime(new Date());
			pocReqPlan.setConfirmType(confirmPlanCheck);
			getPocReqPlanDao().save(pocReqPlan);
		} else {
			procTranRecord = getTaskService().saveTaskAssignUser(procTranRecord, content, nextTasksList);
		}
		getAppBusinessReqDao().save(businessRequest);
		saveDocumentType(businessRequest, procTranRecord, uploads, fileNames, delDocumentIds, procTranRecord.getProcessStep());
	}

	public void rollConfirmPlanTask(String flowTaskId, String content, String confirmPlanCheck) {
		// 保存
		ProcTranRecord procTranRecord = getTaskService().getFlowPvcDao().getTask(Integer.parseInt(flowTaskId), true);
		;
		// 取得业务数据
		BusinessRequest businessRequest = getAppBusinessReqDao().getBusinessRequest(procTranRecord.getProcinstId());
		getTaskService().rollBackTask(procTranRecord, content);
		String reqId = businessRequest.getId().toString();
		User user = ApplicationContextUtil.getUserContextObject().getCurrUser();
		PocReqPlan pocReqPlan = getPocReqPlanDao().getByReqidAndType(reqId, "01");
		pocReqPlan.setConfirmAdv(content);
		pocReqPlan.setConfirmUser(user.getPerson().getName());
		pocReqPlan.setConfirmOptime(new Date());
		pocReqPlan.setConfirmType(confirmPlanCheck);
		getPocReqPlanDao().save(pocReqPlan);
	}

	public void saveProdDataAndCommitTask(String flowTaskId, String content, List<TaskAssignBean> nextTasksList, boolean isCommit, List<File> uploads, List<String> fileNames,
			List<String> delDocumentIds) throws Exception {
		// 保存
		ProcTranRecord procTranRecord = null;
		if (isCommit) {
			procTranRecord = getTaskService().completeTask(flowTaskId, content, nextTasksList);
		} else {
			procTranRecord = getTaskService().saveTaskAssignUser(flowTaskId, content, nextTasksList);
		}
		// 取得业务数据
		ProdAdvReq prodAdvReq = getAppBusinessReqDao().getProdAdvReq(procTranRecord.getProcinstId());
		saveDocumentType(prodAdvReq, procTranRecord, uploads, fileNames, delDocumentIds, procTranRecord.getProcessStep());
	}

	public void saveProdCheckAndCommitTask(String flowTaskId, String content, List<TaskAssignBean> nextTasksList, boolean isCommit, String procinstId, String auditResult, List<File> uploads,
			List<String> fileNames, List<String> delDocumentIds) throws Exception {
		ProdAdvReq prodAdvReq = getAppBusinessReqDao().getProdAdvReq(Integer.valueOf(procinstId));
		if (StringUtils.isNotBlank(auditResult)) {
			prodAdvReq.setTranStatus(auditResult);
			prodAdvReq.setEnd(cn.ffcs.util.converter.DateUtil.getMaxDate());
			getAppBusinessReqDao().save(prodAdvReq);
		}

		ProcTranRecord procTranRecord = null;
		if (isCommit) {
			// 将审核信息传阅给发起人
			// 判断如果 发起人=产品经理 则不传阅
			String startId = prodAdvReq.getStartPerson().getId().toString();
			if (prodAdvReq.getProdPerson() != null) {
				String prodId = prodAdvReq.getProdPerson().getId().toString();
				if (prodId != null && !"".equals(prodId)) {
					if (!startId.equals(prodId)) {
						getTaskService().taskReadingToDo(flowTaskId, "传阅", new String[] { startId });
					}
				}
			}
			procTranRecord = getTaskService().completeTask(flowTaskId, content, nextTasksList);
		} else {
			procTranRecord = getTaskService().saveTaskAssignUser(flowTaskId, content, nextTasksList);
		}
		// 取得业务数据
		saveDocumentType(prodAdvReq, procTranRecord, uploads, fileNames, delDocumentIds, procTranRecord.getProcessStep());
	}

	// 对于附件上传保存

	public void saveDocumentType(BaseEntity obj, ProcTranRecord procTranRecord, List<File> uploads, List<String> fileTypes, List<String> delDocumentIds, ProcessConfigDetail processDetail)
			throws Exception {
		if (delDocumentIds != null && delDocumentIds.size() > 0) {
			// 删除选的文件
			String ids[] = new String[delDocumentIds.size()];
			delDocumentIds.toArray(ids);
			getAppBusinessReqDao().deleteDocuByIds(ids);
		}
		if (uploads != null && uploads.size() > 0) {
			int i = 0;
			for (File file : uploads) {
				byte[] result = FileUtils.readFileToByteArray(file);
				String fileName = file.getName();
				String fullName = fileName;
				String name = fullName.substring(0, fullName.indexOf("."));
				String prefix = fullName.substring(fullName.indexOf(".") + 1, fullName.length());

				ReqDocu reqDocu = new ReqDocu();
				DocContent doc = new DocContent();
				doc.setContent(result);
				getAppBusinessReqDao().save(doc);
				reqDocu.setContent(doc);
				Dict dict = new Dict();
				dict.setId(Integer.valueOf(fileTypes.get(i)));
				reqDocu.setDocType(dict);
				reqDocu.setFullName(fullName);
				reqDocu.setName(name);
				reqDocu.setPrefix(prefix);
				reqDocu.setRefEntity(obj.getClass().getName());
				reqDocu.setRefEntityId(obj.getId().toString());
				reqDocu.setProcessDetail(processDetail);
				reqDocu.setProcinstId(procTranRecord.getProcinstId());
				reqDocu.setRecordId(procTranRecord.getId());
				// 设置基本信息
				setBaseInfo(reqDocu);
				getAppBusinessReqDao().save(reqDocu);
				i++;
			}

			for (File file : uploads) {
				if (file.exists()) {
					FileUtils.forceDelete(file);
				}
			}
		}
	}

	public void saveDoProcess(ReqProgress reqProgress) {
		// 取得节点类型
		ProcTranRecord procTranRecord = getTaskService().getFlowPvcDao().getTask(Integer.valueOf(reqProgress.getRecotdId()));
		ProcessConfigDetail processConfigDetail = procTranRecord.getProcessStep();
		reqProgress.setProcessConfigDetail(processConfigDetail);
		getAppBusinessReqDao().save(reqProgress);
	}

	public void saveDoDelay(ReqDelay reqDelay) {
		// 取得节点类型
		ProcTranRecord procTranRecord = getTaskService().getFlowPvcDao().getTask(Integer.valueOf(reqDelay.getRecotdId()));
		ProcessConfigDetail processConfigDetail = procTranRecord.getProcessStep();
		reqDelay.setProcessConfigDetail(processConfigDetail);
		getAppBusinessReqDao().save(reqDelay);
	}

	/**
	 * 设置实体基本信息: 包括创建人,开始时间,结束时间
	 * 
	 * @param baseEntity
	 */
	protected void setBaseInfo(BaseEntity baseEntity) {
		User currUser = ApplicationContextUtil.getUserContextObject().getCurrUser();
		if (currUser != null) {
			baseEntity.setCreator(currUser.getUserID());
		}
		// 设置有效时间
		baseEntity.setBegin(new Date());
		Long l = Long.valueOf("9783941568000");
		Date end = new Date(l);
		baseEntity.setEnd(end);
	}

	/**
	 * 获取需求编号操作
	 * 
	 * @return
	 */
	public String getReqCode() {
		String nextval = getBusinessRequestService().getNextval("seq_req_num");
		return "FJ" + nextval;
	}

	public Organization getOrgByPerson(Person person) {
		if (person != null && person.getId() != null) {
			return getAppBusinessReqDao().getOrgByPerson(person.getId());
		}
		return null;
	}
    /**
	public void getReqProgressAndDelay(BusinessRequest businessRequest, TaskView taskView) {
		if (businessRequest != null) {
			List<ProcTranRecord> tasklist = taskView.getFlowTaskList();
			List<ReqProgress> reqProgresslist = getAppBusinessReqDao().findReqProgressList(businessRequest.getId());
			List<ReqDelay> reqDelaylist = getAppBusinessReqDao().findReqReqDelayList(businessRequest.getId());

			for (ProcTranRecord procTranRecordTask : tasklist) {
				String id = procTranRecordTask.getId().toString();
				for (ReqProgress reqProgress : reqProgresslist) {
					if (id.equals(reqProgress.getRecotdId())) {
						procTranRecordTask.addReqProgressList(reqProgress);
					}
				}
				for (ReqDelay reqDelay : reqDelaylist) {
					if (id.equals(reqDelay.getRecotdId())) {
						procTranRecordTask.addReqDelayList(reqDelay);
					}
				}
			}
		}
		//return taskView;
	}**/

	public void getReqProgressAndDelay(BusinessRequest businessRequest, List<ProcTranRecord> tasklist) {
		if (businessRequest != null) {
			List<ReqProgress> reqProgresslist = getAppBusinessReqDao().findReqProgressList(businessRequest.getId());
			List<ReqDelay> reqDelaylist = getAppBusinessReqDao().findReqReqDelayList(businessRequest.getId());

			for (ProcTranRecord procTranRecordTask : tasklist) {
				String id = procTranRecordTask.getId().toString();
				for (ReqProgress reqProgress : reqProgresslist) {
					if (id.equals(reqProgress.getRecotdId())) {
						procTranRecordTask.addReqProgressList(reqProgress);
					}
				}
				for (ReqDelay reqDelay : reqDelaylist) {
					if (id.equals(reqDelay.getRecotdId())) {
						procTranRecordTask.addReqDelayList(reqDelay);
					}
				}
			}
		}
	}
	
	public ProcTranRecord startImproveFlow(String reqId) {

		return null;
	}

	/**
	 * 分解需求单
	 */
	public void saveResoleBsReq(String reqCode, List<BusinessRequest> bsReqList, String processConfigId) {
		// TODO Auto-generated method stub
		User user = ApplicationContextUtil.getUserContextObject().getCurrUser();
		ProdAdvReq prodAdvReq = getAppBusinessReqDao().getProdAdvReqById(Integer.valueOf(reqCode));
		if ("PASS".equalsIgnoreCase(prodAdvReq.getTranStatus()) || "DOPASS".equalsIgnoreCase(prodAdvReq.getTranStatus())) {
			prodAdvReq.setOpType("FJ");
			prodAdvReq.setTranStatus("PROD");
			List<TaskAssignBean> nextTasksList = null;
			TaskAssignBean taskAssignBean = null;
			String reqCodeArr = "";
			for (BusinessRequest businessRequest : bsReqList) {
				String startPersonId = businessRequest.getStartPersonObj().getId().toString();
				nextTasksList = new ArrayList<TaskAssignBean>();
				taskAssignBean = new TaskAssignBean();
				taskAssignBean.setTaskNodeId(null);
				taskAssignBean.setUserId(String.valueOf(businessRequest.getProdPerson().getId()));
				nextTasksList.add(taskAssignBean);
				businessRequest.setReqCode(getReqCode());
				ProcessInstView processInstView = getProcessPvcService().startProcessInst(processConfigId, user.getPerson(), nextTasksList, true, startPersonId);
				businessRequest.setProcinstId(processInstView.getProcessStatus().getProcinstId());
				if (prodAdvReq.getAdvanTime() != null) {
					businessRequest.setAdvanTime(prodAdvReq.getAdvanTime());
				}
				getAppBusinessReqDao().save(businessRequest);
				copyReqDocu(prodAdvReq, businessRequest);
				reqCodeArr += businessRequest.getId() + ",";
			}
			prodAdvReq.setChildAreq(reqCodeArr);
			getAppBusinessReqDao().save(prodAdvReq);
		} else {
			throw new FlowPvcException("对不起，分解失败！");
		}
	}

	/**
	 * 启动产品改进需求流程
	 * 
	 * @param reqId
	 * @param processConfigId
	 */
	public BusinessRequest startReq(String reqId, String processConfigId, HttpServletRequest request) {

		ProdAdvReq prodAdvReq = getAppBusinessReqDao().getProdAdvReqById(Integer.valueOf(reqId));
		BusinessRequest businessRequest = new BusinessRequest();
		String name = request.getParameter("businessRequest.name");
		String content = request.getParameter("businessRequest.content");
		String personId = request.getParameter("prodPerson");
		Person person = getAppBusinessReqDao().getPerson(Integer.valueOf(personId));
		Organization organization = getAppBusinessReqDao().getOrgByPerson(Integer.valueOf(personId));
		prodAdvReq.setProdPerson(person);
		prodAdvReq.setProdDept(organization);
		prodAdvReq.setName(name);
		prodAdvReq.setContent(content);

		businessRequest.setName(prodAdvReq.getName());
		businessRequest.setContent(prodAdvReq.getContent());
		businessRequest.setStartPersonObj(prodAdvReq.getStartPerson());
		businessRequest.setStartPerson(prodAdvReq.getStartPerson().getName());
		businessRequest.setStartDeptObj(prodAdvReq.getStartDept());
		businessRequest.setStartDept(prodAdvReq.getStartDept().getName());
		businessRequest.setReqCode(prodAdvReq.getReqCode());
		businessRequest.setProdPerson(prodAdvReq.getProdPerson());
		businessRequest.setProdDept(prodAdvReq.getProdDept());

		businessRequest.setImportance(request.getParameter("importanceId"));
		businessRequest.setType(request.getParameter("typeId"));
		businessRequest.setProcinstType("02");
		businessRequest.setEnd(cn.ffcs.util.converter.DateUtil.getMaxDate());

		if (prodAdvReq.getBegin() != null) {
			businessRequest.setBegin(prodAdvReq.getBegin());
		}
		if (prodAdvReq.getAdvanTime() != null) {
			businessRequest.setAdvanTime(prodAdvReq.getAdvanTime());
		}
		User user = ApplicationContextUtil.getUserContextObject().getCurrUser();
		List<TaskAssignBean> nextTasksList = null;
		TaskAssignBean taskAssignBean = null;
		nextTasksList = new ArrayList<TaskAssignBean>();
		String taskNodeId = request.getParameter("taskNodeId");

		taskAssignBean = new TaskAssignBean();
		taskAssignBean.setTaskNodeId(taskNodeId);
		taskAssignBean.setUserId(String.valueOf(businessRequest.getProdPerson().getId()));
		nextTasksList.add(taskAssignBean);
		String startPersonId = businessRequest.getStartPersonObj().getId().toString();
		ProcessInstView processInstView = getProcessPvcService().startProcessInst(processConfigId, user.getPerson(), nextTasksList, true, startPersonId);
		businessRequest.setProcinstId(processInstView.getProcTranRecord().getProcinstId());
		getAppBusinessReqDao().save(businessRequest);
		prodAdvReq.setOpType("QD");
		prodAdvReq.setTranStatus("PROD");
		prodAdvReq.setChildAreq(businessRequest.getId().toString());
		prodAdvReq.setRelaReq(businessRequest);
		getAppBusinessReqDao().save(prodAdvReq);

		copyReqDocu(prodAdvReq, businessRequest);

		return businessRequest;
	}

	@SuppressWarnings("unchecked")
	public void copyReqDocu(BaseEntity fromEntity, BusinessRequest toEntity) {
		List<ReqDocu> list = getBusinessRequestService().getReqDocuDAO().findByEntity(fromEntity);
		if (list == null || list.size() == 0)
			return;
		for (int i = 0; i < list.size(); i++) {
			ReqDocu fromReqDocu = list.get(i);
			ReqDocu toReqDocu = new ReqDocu();
			toReqDocu.setRefEntity(toEntity.getClass().getName());
			toReqDocu.setRefEntityId(toEntity.getId().toString());

			toReqDocu.setBegin(fromReqDocu.getBegin());
			toReqDocu.setEnd(fromReqDocu.getEnd());
			toReqDocu.setContent(fromReqDocu.getContent());
			toReqDocu.setCreator(fromReqDocu.getCreator());
			toReqDocu.setDocType(fromReqDocu.getDocType());
			toReqDocu.setDocTypeName(fromReqDocu.getDocTypeName());
			toReqDocu.setFullName(fromReqDocu.getFullName());
			toReqDocu.setLength(fromReqDocu.getLength());
			toReqDocu.setName(fromReqDocu.getName());
			toReqDocu.setPrefix(fromReqDocu.getPrefix());
			toReqDocu.setProcessDetail(fromReqDocu.getProcessDetail());
			toReqDocu.setProcinstId(toEntity.getProcinstId());
			// toReqDocu.setRecordId(toEntity.getProcTranRecord().getId());
			toReqDocu.setRecordId(toReqDocu.getRecordId());
			toReqDocu.setVersion(fromReqDocu.getVersion());
			getBusinessRequestService().getReqDocuDAO().save(toReqDocu);
		}

	}

	/**
	 * 合并需求单
	 * 
	 * @param reqCode
	 * @param businessRequest
	 * @param processConfigId
	 */
	public Integer saveMergeBsReq(String reqCode, BusinessRequest businessRequest, String processConfigId) {
		User user = ApplicationContextUtil.getUserContextObject().getCurrUser();
		List<TaskAssignBean> nextTasksList = null;
		TaskAssignBean taskAssignBean = null;
		nextTasksList = new ArrayList<TaskAssignBean>();
		taskAssignBean = new TaskAssignBean();
		taskAssignBean.setTaskNodeId(null);
		taskAssignBean.setUserId(String.valueOf(businessRequest.getProdPerson().getId()));
		nextTasksList.add(taskAssignBean);
		String startPersonId = businessRequest.getStartPersonObj().getId().toString();
		ProcessInstView processInstView = getProcessPvcService().startProcessInst(processConfigId, user.getPerson(), nextTasksList, true, startPersonId);
		businessRequest.setProcinstId(processInstView.getProcessStatus().getProcinstId());
		getAppBusinessReqDao().save(businessRequest);
		String[] codes = reqCode.split(",");
		for (int i = 0; i < codes.length; i++) {

			ProdAdvReq prodAdvReq = getAppBusinessReqDao().getProdAdvReqByReqCode(codes[i]);
			prodAdvReq.setOpType("HB");
			prodAdvReq.setTranStatus("PROD");
			prodAdvReq.setChildAreq(businessRequest.getId().toString());
			getAppBusinessReqDao().save(prodAdvReq);
			copyReqDocu(prodAdvReq, businessRequest);
		}
		return processInstView.getProcessStatus().getProcinstId();
	}

	public String getFlowReqDelayProcessId() {
		String name = getConfigBean().getFlowReqDelayTag();
		Dict flowDict = getAppBusinessReqDao().getDict(name);
		if (flowDict != null) {
			return flowDict.getKeyValue();
		}
		return "10";
	}

	public String getFlowImproveReqProcessId() {
		String name = getConfigBean().getFlowImproveReqTag();
		Dict flowDict = getAppBusinessReqDao().getDict(name);
		if (flowDict != null) {
			return flowDict.getKeyValue();
		}
		return "5";
	}

	public String getFlowFastImproveReqProcessId() {
		String name = getConfigBean().getFlowFastImproveReqTag();
		Dict flowDict = getAppBusinessReqDao().getDict(name);
		if (flowDict != null) {
			return flowDict.getKeyValue();
		}
		return "108";
	}
	
	public String getFlowImproveReqCheckProcessId() {
		String name = getConfigBean().getFlowImproveCheckTag();
		Dict flowDict = getAppBusinessReqDao().getDict(name);
		if (flowDict != null) {
			return flowDict.getKeyValue();
		}
		return "7";
	}

	public String getFlowContractRemindProcessId() {
		String name = getConfigBean().getContractRemindProcessTag();
		Dict flowDict = getAppBusinessReqDao().getDict(name);
		if (flowDict != null) {
			return flowDict.getKeyValue();
		}
		return "9";
	}

	public String getFlowNewReqProcessId() {
		String name = getConfigBean().getFlowNewReqTag();
		Dict flowDict = getAppBusinessReqDao().getDict(name);
		if (flowDict != null) {
			return flowDict.getKeyValue();
		}
		return "4";
	}

	public String getFlowContractBussOutProcessId() {
		String name = getConfigBean().getContractBussOutProcessTag();
		Dict flowDict = getAppBusinessReqDao().getDict(name);
		if (flowDict != null) {
			return flowDict.getKeyValue();
		}
		return "110";
	}
	
	public String getAppSmsProcessId() {
		String name = getConfigBean().getAppSmsProcessTag();
		Dict flowDict = getAppBusinessReqDao().getDict(name);
		if (flowDict != null) {
			return flowDict.getKeyValue();
		}
		return "112";
	}
	
	
	public List<Person> findProdListByRole() {
		List<Person> prodList = taskService.getFlowPvcDao().findPersonByRoleName(PROD_ROLE_NAME, true);
		return prodList;
	}

	public boolean checkPersonIsProd(String personId) {
		boolean isProd = taskService.getFlowPvcDao().checkPersonHasRole(PROD_ROLE_NAME, personId);
		return isProd;
	}
	
	public void tranferData() {

		//

	}

	public AppBusinessReqDao getAppBusinessReqDao() {
		return appBusinessReqDao;
	}

	public void setAppBusinessReqDao(AppBusinessReqDao appBusinessReqDao) {
		this.appBusinessReqDao = appBusinessReqDao;
	}

	@SuppressWarnings("unchecked")
	public BusinessRequestService getBusinessRequestService() {
		return businessRequestService;
	}

	@SuppressWarnings("unchecked")
	public void setBusinessRequestService(BusinessRequestService businessRequestService) {
		this.businessRequestService = businessRequestService;
	}

	public ProcessPvcService getProcessPvcService() {
		return processPvcService;
	}

	public void setProcessPvcService(ProcessPvcService processPvcService) {
		this.processPvcService = processPvcService;
	}

	public TaskService getTaskService() {
		return taskService;
	}

	public void setTaskService(TaskService taskService) {
		this.taskService = taskService;
	}

	public ConfigBean getConfigBean() {
		return configBean;
	}

	public void setConfigBean(ConfigBean configBean) {
		this.configBean = configBean;
	}

	public PocReqPlanDao getPocReqPlanDao() {
		return pocReqPlanDao;
	}

	public void setPocReqPlanDao(PocReqPlanDao pocReqPlanDao) {
		this.pocReqPlanDao = pocReqPlanDao;
	}

}
